package com.gxuwz.medical.web.servlet.user;

import java.io.IOException;
import java.sql.Connection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gxuwz.medical.dao.UserDao;
import com.gxuwz.medical.database.DbUtil;
import com.gxuwz.medical.domain.user.User;
import com.gxuwz.medical.tools.JsonUtil;
import com.gxuwz.medical.tools.PageBean;
import com.gxuwz.medical.tools.ResponseUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class UserListServlet extends HttpServlet {

	DbUtil dbUtil = new DbUtil();
	UserDao userDao = new UserDao();

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		System.out.println("用户有啦");
		// 获取前台传来的查询数据
		String id = request.getParameter("id");
		String userid = request.getParameter("userid");
		String pwd = request.getParameter("pwd");
		String fullname = request.getParameter("fullname");

		// 构造一个Student
		User user = new User();
		if (userid != null) {
			user.setUserid(userid);
			user.setPwd(pwd);
			user.setFullname(fullname);

		}

		String page = request.getParameter("page"); // 第几页
		String rows = request.getParameter("rows"); // 每页记录数

		PageBean pageBean = new PageBean(Integer.parseInt(page), Integer.parseInt(rows)); // 得到PageBean
		Connection con = null;

		try {
			con = dbUtil.getCon();
			JSONObject result = new JSONObject();
			JSONArray jsonArray = JsonUtil.formatRsToJsoarray(userDao.userList(pageBean, user)); // 用JSONArray返回数据
			System.out.println(jsonArray);
			int total = userDao.userCount(user); // 获取学生总数
			result.put("rows", jsonArray); // 把JSONArray放入结果JSONObject中
			result.put("total", total); // 把total总数也放入结果JSONObject中
			ResponseUtil.write(response, result); // 把数据写入response
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				dbUtil.closeCon(con);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
